package com.wwwarehouse.contract.orders.place_order;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.adapter.pop.BubblePopAdapter;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.eventbus_event.DrawerMultipleCompleteEvent;
import com.wwwarehouse.common.fragment.CommonBasePagerFragment;
import com.wwwarehouse.common.fragment.DeskDrawerMultipleFragment;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.contract.bean.BrowseGoodsFilterBean;
import com.wwwarehouse.contract.bean.PlaceOrdersBrowseConfirmBean;
import com.wwwarehouse.contract.bean.PlaceOrdersBrowseEvent;
import com.wwwarehouse.contract.bean.PlaceOrdersBrowseGoodsBean;
import com.wwwarehouse.contract.core.ContractConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

import static com.alibaba.fastjson.JSON.parseObject;


/**
 * 下单->浏览商品
 * Created by ShineF on 2017/10/18 0018.
 */
@Route(path = "/contract/PlaceOrdersBrowseGoodsPagerFragment")
public class PlaceOrdersBrowseGoodsPagerFragment extends CommonBasePagerFragment {

    private List<FilterBean> sortList;
    private ArrayList<FilterBean> mFilterList;
    private String mSearchText = "";
    private List<BrowseGoodsFilterBean.PROVIDERBean> mProviderList;
    private String mSort = "";
    private ArrayList<String> filterContentList;
    private String mDemandId;
    private RefreshReceiver mReceiver;
    private int mShoppingNum;

    @Override
    public void requestDatas() {
        super.requestDatas();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mReceiver = new RefreshReceiver();
        IntentFilter filter = new IntentFilter("refreshOrdersList");
        mActivity.registerReceiver(mReceiver, filter);
        Bundle bundle = getArguments();
        if (null != bundle) {
            CardDeskFunctionResponseBean.TaskBean mBean =
                    (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            if (null != mBean) {
                mDemandId = mBean.getBusinessId();
            }
        }
//        if (mDemandId == null) {
//            mDemandId = "10001651";
////            mDemandId = "10001641";
//        }
        hideConfirmButton();
        requestHttp("", new ArrayList<String>(), mSort);
        mFilterList = new ArrayList<>();
        filterContentList = new ArrayList<>();
        sortList = new ArrayList<>();
        sortList.add(new FilterBean(true, getString(R.string.place_data)));
        sortList.add(new FilterBean(false, getString(R.string.stock_1)));
        sortList.add(new FilterBean(false, getString(R.string.stock_2)));
        sortList.add(new FilterBean(false, getString(R.string.stock_4)));
        sortList.add(new FilterBean(false, getString(R.string.stock_3)));
        Map<String, Object> map = new HashMap<>();
        map.put("codeType", "PROVIDER");
        loadData(ContractConstant.GOODS_DETAILS_FILTER, map, 2);
        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShoppingNum <= 0) {
                    ToastUtils.showToast(R.string.shopping_no);
                    return;
                }
                mConfirmBtn.setText(mShoppingNum + "\n去下单");
                ((BaseCardDeskActivity) mActivity).hideSearchTitle();
                Bundle bundle = new Bundle();
                bundle.putString(ContractConstant.KEY_CONSTRACT_PLACE_ORDER_DEMANID, mDemandId);
                ShoppingCartViewPagerFragment fragment = new ShoppingCartViewPagerFragment();
                fragment.setArguments(bundle);
                pushFragment(fragment);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        mActivity.unregisterReceiver(mReceiver);
    }

    public void requestHttp(String name, List<String> list, String sort) {
        Map<String, Object> map = new HashMap<>();
//        map.put("demandId", "10001589");
        map.put("demandId", mDemandId);
        map.put("page", "1");
        map.put("search", name);
        map.put("size", "5");
        map.put("sort", sort);
        map.put("supplierType", list);
        loadData(ContractConstant.PLACE_ORDERS_BROWSE_GOODS, map, 1);
    }

    @Override
    public void sortClick(View anchor) {
        super.sortClick(anchor);
        if (peekFragment() instanceof PlaceOrdersBrowseGoodsPagerFragment) {
            showPopupWindow(anchor);
        }
    }

    @Override
    public void filterClick() {
        super.filterClick();
        ((BaseCardDeskActivity) mActivity).showDrawerLayout();
    }

    @Override
    public void onRefreshListener() {
        requestHttp(mSearchText, filterContentList, mSort);
    }

    @Override
    public void onLoadSuccess(String data, int what) {
        if (what == 1) {
            PlaceOrdersBrowseGoodsBean bean = parseObject(data, PlaceOrdersBrowseGoodsBean.class);
            showConfirmButton();
            if (null != bean) {
                Bundle bundle = new Bundle();
                try {
                    bundle.putString("sortName", mSort);
                    bundle.putStringArrayList("filtName", filterContentList);
                    bundle.putString("searchName", mSearchText);
                    bundle.putInt("shoppingNum", bean.getItemCount());
                    bundle.putString("demandId", mDemandId);
                    setData(bean.getTotal(), 5, PlaceOrdersBrowseGoodsDetailsFragment.class.getName()
                            , bundle, bean.getItemList());
                    setChildView();
                    if (!TextUtils.isEmpty(mSearchText)) {
                        showConfirmButton();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showToast("数据源为空");
                }
            }
        } else if (what == 2) {
            BrowseGoodsFilterBean bean = JSON.parseObject(data, BrowseGoodsFilterBean.class);
            if (null != bean) {
                setFilterBean(bean);
            }
        }

    }

    public void setTitle() {
        if (peekFragment() instanceof PlaceOrdersBrowseGoodsPagerFragment) {
            mActivity.setTitle(getString(R.string.browse_product));
        }
    }

    private void setFilterBean(BrowseGoodsFilterBean bean) {
        mProviderList = bean.getPROVIDER();
        if (null == mProviderList) {
            return;
        }
        if (mProviderList.size() == 0) {
            return;
        }
        for (BrowseGoodsFilterBean.PROVIDERBean providerBean : mProviderList) {
            mFilterList.add(new FilterBean(false, providerBean.getName()));
        }
        DeskDrawerMultipleFragment deskDrawerMultipleFragment = DeskDrawerMultipleFragment.newInstance("供应商类型", mFilterList, 3);
        ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
    }

    @Override
    public void onLoadError(String errorInfo) {

    }


    public void showPopupWindow(View view) {

        PopUpUtils.showBubbleDown(view, mActivity, sortList, new BubblePopAdapter.OnPopListClickListener() {
            @Override
            public void setOnItemClickListener(int i, View view) {
                for (FilterBean filterBean : sortList) {
                    filterBean.setSelect(false);
                }
                sortList.get(i).setSelect(true);
                if (i == 0) { //发布日期从近到远
                    mSort = "start_valid_time desc";
                } else if (i == 1) { //库存从多到少
                    mSort = "inventory_qty desc";
                } else if (i == 2) { //库存从少到多
                    mSort = "inventory_qty";
                } else if (i == 3) { //单价从高到底
                    mSort = "pb_price desc";
                } else if (i == 4) { //单价从低到高
                    mSort = "pb_price ";
                }
                requestHttp(mSearchText, filterContentList, mSort);
            }
        });
    }

    @Override
    public void textNoRealChanged(String text) {
        super.textNoRealChanged(text);
        this.mSearchText = text;
        requestHttp(text, new ArrayList<String>(), mSort);
    }

    public void onEventMainThread(DrawerMultipleCompleteEvent event) {
        if (event != null && event.getSelectedPositionSet() != null && peekFragment() instanceof PlaceOrdersBrowseGoodsPagerFragment) {
            filterContentList.clear();
            Set<Integer> selectedPositionSet = event.getSelectedPositionSet();
            if (!selectedPositionSet.isEmpty()) {
                for (Integer integer : selectedPositionSet) {
                    filterContentList.add(mProviderList.get(integer).getCode());
                    LogUtils.showErrLog(mProviderList.get(integer).getName());
                }
            }
            requestHttp(mSearchText, filterContentList, mSort);
        }
    }

    public void onEventMainThread(PlaceOrdersBrowseEvent event) {
        if (peekFragment() instanceof PlaceOrdersBrowseGoodsPagerFragment && event.getType().equals("gotoOrders")) {
            mShoppingNum = event.getShoppintNum();
            if (mShoppingNum != 0) {
                mConfirmBtn.setText(mShoppingNum + "\n去下单");
            } else {
                mConfirmBtn.setText("去下单");
            }
        }
    }

    public void setChildView() {
        for (Fragment fragment : mFragmentList) {
            ((PlaceOrdersBrowseGoodsDetailsFragment) fragment).setViewAndViewGroup(getConfirmBtn(), getParentLayout());
        }
    }

    @Override
    public void cancelClick() {
        super.cancelClick();
        mSearchText = "";
        requestHttp(mSearchText, filterContentList, mSort);
    }

    class RefreshReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("refreshOrdersList")) {
                mShoppingNum = intent.getIntExtra("shopNum", mShoppingNum);
                if (mShoppingNum == 0) {
                    mConfirmBtn.setText("去下单");
                } else {
                    mConfirmBtn.setText(mShoppingNum + "\n去下单");
                }
                EventBus.getDefault().post(new PlaceOrdersBrowseConfirmBean(mShoppingNum, "browseShoppintNum"));
//                requestHttp(mSearchText, filterContentList, mSort);
            }
        }
    }
}
